<template>
  <div>
    <el-main
      v-loading="loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
    >
      <!--查询条件-->
      <el-form ref="queryForm" size="small" :inline="true">
        <el-form-item label="定时刷新时间(秒)">
          <el-input
            v-model="newRefreshTime"
            placeholder="请输入刷新时间，单位秒"
            clearable
            :disabled="editReFreshFlag"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button v-if="editReFreshFlag" type="primary" icon="el-icon-search" size="mini" @click="editNewRefreshTime">编辑</el-button>
          <el-button v-if="!editReFreshFlag" type="primary" icon="el-icon-search" size="mini" @click="commitNewRefreshTime">确定</el-button>
          <el-button v-if="!editReFreshFlag" icon="el-icon-refresh" size="mini" @click="cancelNewRefreshTime">取消</el-button>
        </el-form-item>
      </el-form>

      <!--温度-->
      <el-row class="mb8">
        <el-col :span="24" :xs="24">
          <el-card class="box-card">
            <!--查询条件-->
            <el-form ref="temperature" size="small" :inline="true">
              <el-form-item label="收集时间">
                <el-date-picker
                  v-model="tRangeTime"
                  style="width: 360px"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getTemperature()">搜索</el-button>
                <el-button
                  v-if="temperatureRefresh"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="temperatureResetTimedRefresh"
                >关闭定时刷新</el-button>
                <el-button
                  v-if="!temperatureRefresh"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="temperatureResetTimedRefresh"
                >开启定时刷新</el-button>
              </el-form-item>
            </el-form>

            <div id="temperature" style="width: 100%;height:400px;" />
          </el-card>
        </el-col>
      </el-row>

      <!--湿度-->
      <el-row :gutter="20" class="mb8">
        <el-col :span="24" :xs="24">
          <el-card class="box-card">
            <!--查询条件-->
            <el-form ref="humidity" size="small" :inline="true">
              <el-form-item label="收集时间">
                <el-date-picker
                  v-model="hRangeTime"
                  style="width: 360px"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getHumidity">搜索</el-button>
                <el-button
                  v-if="humidityRefresh"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="humidityResetTimedRefresh"
                >关闭定时刷新</el-button>
                <el-button
                  v-if="!humidityRefresh"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="humidityResetTimedRefresh"
                >开启定时刷新</el-button>
              </el-form-item>
            </el-form>
            <div id="humidity" style="width: 100%;height:400px;" />
          </el-card>
        </el-col>
      </el-row>

      <!--光照强度-->
      <el-row :gutter="20" class="mb8">
        <el-col :span="24" :xs="24">
          <el-card class="box-card">
            <!--查询条件-->
            <el-form ref="light" size="small" :inline="true">
              <el-form-item label="收集时间">
                <el-date-picker
                  v-model="lRangeTime"
                  style="width: 360px"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getLight">搜索</el-button>
                <el-button
                  v-if="lightRefresh"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="lightResetTimedRefresh"
                >关闭定时刷新</el-button>
                <el-button
                  v-if="!lightRefresh"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="lightResetTimedRefresh"
                >开启定时刷新</el-button>
              </el-form-item>
            </el-form>
            <div id="light" style="width: 100%;height:400px;" />
          </el-card>
        </el-col>
      </el-row>

      <!--二氧化碳浓度-->
      <el-row :gutter="20" class="mb8">
        <el-col :span="24" :xs="24">
          <el-card class="box-card">
            <!--查询条件-->
            <el-form ref="co2" size="small" :inline="true">
              <el-form-item label="收集时间">
                <el-date-picker
                  v-model="cRangeTime"
                  style="width: 360px"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  type="datetimerange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="getCO2">搜索</el-button>
                <el-button
                  v-if="CO2Refresh"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="CO2ResetTimedRefresh"
                >关闭定时刷新</el-button>
                <el-button
                  v-if="!CO2Refresh"
                  icon="el-icon-refresh"
                  size="mini"
                  @click="CO2ResetTimedRefresh"
                >开启定时刷新</el-button>
              </el-form-item>
            </el-form>
            <div id="co2" style="width: 100%;height:400px;" />
          </el-card>
        </el-col>
      </el-row>

    </el-main>
  </div>
</template>

<script>
import api from '@/api/hardware/data/data'
import MyEchartsOption from '@/views/forms/chart/myEchartsOption'

export default {
  name: 'Chart',
  data() {
    return {
      loading: true,

      tRangeTime: [],
      hRangeTime: [],
      lRangeTime: [],
      cRangeTime: [],
      queryParams: {
        dataType: null,
        beginTime: '',
        endTime: ''
      },

      // echarts图表对象
      temperatureChart: {},
      humidityOptionChart: {},
      lightOptionChart: {},
      CO2OptionChart: {},

      temperatureOption: {},

      // 定时刷新控制
      temperatureRefresh: false,
      humidityRefresh: false,
      lightRefresh: false,
      CO2Refresh: false,
      // 定时刷新时间
      refreshTime: 60000,
      newRefreshTime: 60,
      editReFreshFlag: true,

      // 定时器对象
      myTimer: null
    }
  },

  // 页面渲染之后获取数据
  async mounted() {
    try {
      this.$message.info('拼命加载数据，为您生成图表中，请稍候')
      this.initDataEcharts()
      await this.getTemperature()
      await this.getHumidity()
      await this.getLight()
      await this.getCO2()
      this.$message.success('恭喜，所有数据加载成功！')
    } finally {
      this.loading = false
    }
  },

  // 关闭页面，清除定时器
  beforeDestroy() {
    clearInterval(this.myTimer)
  },

  methods: {

    /**
     * 显示编辑刷新时间
     */
    editNewRefreshTime() {
      this.editReFreshFlag = false
    },

    /**
     * 取消编辑定时刷新时间
     */
    cancelNewRefreshTime() {
      this.newRefreshTime = this.refreshTime / 1000
      this.editReFreshFlag = true
    },

    /**
     * 提交新的刷新时间
     */
    commitNewRefreshTime() {
      if (this.newRefreshTime === null || this.newRefreshTime === '' || Number(this.newRefreshTime) < 1) {
        this.$message.error('请设置时间至少为1秒钟')
        return
      }
      if (Number(this.newRefreshTime) % 1 !== 0) {
        this.$message.error('请输入正整数')
        return
      }
      this.editReFreshFlag = true
      this.refreshTime = this.newRefreshTime * 1000
      clearInterval(this.myTimer)
      this.myTimer = setInterval(this.timedRefresh, this.refreshTime)
    },

    /**
     * 温度定时刷新开启或关闭
     */
    temperatureResetTimedRefresh() {
      this.temperatureRefresh = !this.temperatureRefresh
      if (this.temperatureRefresh) {
        this.$message.info('定时刷新已开启')
      } else {
        this.$message.info('定时刷新已关闭')
      }
      clearInterval(this.myTimer)
      this.myTimer = setInterval(this.timedRefresh, this.refreshTime)
    },

    /**
     * 湿度定时刷新开启或关闭
     */
    humidityResetTimedRefresh() {
      this.humidityRefresh = !this.humidityRefresh
      if (this.humidityRefresh) {
        this.$message.info('定时刷新已开启')
      } else {
        this.$message.info('定时刷新已关闭')
      }
      clearInterval(this.myTimer)
      this.myTimer = setInterval(this.timedRefresh, this.refreshTime)
    },

    /**
     * 光照强度定时刷新开启或关闭
     */
    lightResetTimedRefresh() {
      this.lightRefresh = !this.lightRefresh
      if (this.lightRefresh) {
        this.$message.info('定时刷新已开启')
      } else {
        this.$message.info('定时刷新已关闭')
      }
      clearInterval(this.myTimer)
      this.myTimer = setInterval(this.timedRefresh, this.refreshTime)
    },

    /**
     * 二氧化碳浓度定时刷新开启或关闭
     */
    CO2ResetTimedRefresh() {
      this.CO2Refresh = !this.CO2Refresh
      if (this.CO2Refresh) {
        this.$message.info('定时刷新已开启')
      } else {
        this.$message.info('定时刷新已关闭')
      }
      clearInterval(this.myTimer)
      this.myTimer = setInterval(this.timedRefresh, this.refreshTime)
    },

    /**
     * 定时刷新
     */
    async timedRefresh() {
      if (this.temperatureRefresh) {
        await this.getTemperature()
      }
      if (this.humidityRefresh) {
        await this.getHumidity()
      }
      if (this.lightRefresh) {
        await this.getLight()
      }
      if (this.CO2Refresh) {
        await this.getCO2()
      }
    },

    /**
     * 初始化echarts
     */
    initDataEcharts() {
      this.temperatureChart = this.$echarts.init(document.getElementById('temperature'))
      const temperatureOption = MyEchartsOption.getOption('环境温度数据', '°C', '温度')
      this.temperatureChart.setOption(temperatureOption)

      this.humidityOptionChart = this.$echarts.init(document.getElementById('humidity'))
      const humidityOption = MyEchartsOption.getOption('环境湿度数据', 'RH', '湿度')
      this.humidityOptionChart.setOption(humidityOption)

      this.lightOptionChart = this.$echarts.init(document.getElementById('light'))
      const lightOption = MyEchartsOption.getOption('环境光照强度数据', 'lx', '光照强度')
      this.lightOptionChart.setOption(lightOption)

      this.CO2OptionChart = this.$echarts.init(document.getElementById('co2'))
      const CO2Option = MyEchartsOption.getOption('环境二氧化碳浓度数据', 'ppm', '二氧化碳浓度')

      this.CO2OptionChart.setOption(CO2Option)
    },

    /**
     * 获取温度数据
     *
     * @returns {Promise<void>}
     */
    async getTemperature() {
      // 发请求，获取数据
      this.setMyQueryParams(1, this.tRangeTime)
      const temperature = await api.echartsData(this.queryParams)
      // 挂载数据
      this.temperatureChart.setOption({
        xAxis: {
          data: temperature.data.map(value => value.date)
        },
        series: [{
          data: temperature.data.map(value => value.value)
        }]
      })
    },

    /**
     * 获取湿度数据
     *
     * @returns {Promise<void>}
     */
    async getHumidity() {
      // 发请求，获取数据
      this.setMyQueryParams(2, this.hRangeTime)
      const humidity = await api.echartsData(this.queryParams)
      // 挂载数据
      this.humidityOptionChart.setOption({
        xAxis: {
          data: humidity.data.map(value => value.date)
        },
        series: [{
          data: humidity.data.map(value => value.value)
        }]
      })
    },

    /**
     * 获取光照数据
     *
     * @returns {Promise<void>}
     */
    async getLight() {
      // 发请求，获取数据
      this.setMyQueryParams(3, this.lRangeTime)
      const light = await api.echartsData(this.queryParams)
      // 挂载数据
      this.lightOptionChart.setOption({
        xAxis: {
          data: light.data.map(value => value.date)
        },
        series: [{
          data: light.data.map(value => value.value)
        }]
      })
    },

    /**
     * 获取二氧化碳浓度数据
     *
     * @returns {Promise<void>}
     */
    async getCO2() {
      // 发请求，获取数据
      this.setMyQueryParams(4, this.cRangeTime)
      const CO2 = await api.echartsData(this.queryParams)
      // 挂载数据
      this.CO2OptionChart.setOption({
        xAxis: {
          data: CO2.data.map(value => value.date)
        },
        series: [{
          data: CO2.data.map(value => value.value)
        }]
      })
    },

    setMyQueryParams(datatype, rangeTime) {
      if (rangeTime == null) {
        this.queryParams.beginTime = null
        this.queryParams.endTime = null
      } else {
        if (rangeTime[0] === rangeTime[1]) {
          this.queryParams.beginTime = rangeTime[0]
          this.queryParams.endTime = null
        } else {
          this.queryParams.beginTime = rangeTime[0]
          this.queryParams.endTime = rangeTime[1]
        }
      }
      this.queryParams.dataType = datatype
    }
  }
}

</script>

<style scoped>
</style>
